<template>
  <div class="app-container">


    <!--添加数据对话框表单-->
    <el-dialog ref="activityForm"
      title="添加活动"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose">
      <el-form ref="activityForm" :model="activityForm" :rules="rules" label-width="100px" size="mini">

        <el-form-item label="活动名称" prop="name">
          <el-input v-model="activityForm.name" />
        </el-form-item>

        <el-form-item label="活动内容" prop="content">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入内容"
            maxlength="500"
            show-word-limit
            v-model="activityForm.content">
          </el-input>
        </el-form-item>

        <el-form-item label="活动地点" prop="place">
          <el-input v-model="activityForm.place" />
        </el-form-item>
        <el-form-item label="活动举办方" prop="org">
          <el-input v-model="activityForm.org" />
        </el-form-item>

        <el-form-item label="活动人数" prop="people">
          <el-input v-model.number="activityForm.people" />
        </el-form-item>

        <el-form-item label="活动时间" prop="beginTime" size="medium">
          <!-- <el-date-picker type="date" placeholder="选择日期" v-model="activityForm.beginTime" style=""></el-date-picker> -->
          <el-date-picker
            v-model="activityForm.beginTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>

        </el-form-item>

        <el-form-item label="活动积分" prop="score">
          <el-input v-model.number="activityForm.score" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('activityForm')">提交</el-button>
        <!-- <el-button @click="dialogVisible = false">取消修改</el-button> -->
        <el-button @click="resetForm('activityForm')">取消</el-button>
      </div>
    </el-dialog>

    <!-- 修改数据对话框 -->
    <el-dialog ref="activity"
      title="编辑活动"
      :visible.sync="dialogVisible2"
      width="40%">
      <el-form ref="activity" :model="activity" label-width="100px" size="mini">

        <el-form-item label="活动名称" prop="name">
          <!-- <el-input v-model="activity.name" /> -->
          {{ activity.name }}
        </el-form-item>

        <el-form-item label="活动内容" prop="content">
          <!-- <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4}"
            placeholder="请输入内容"
            maxlength="500"
            show-word-limit
            v-model="activity.content">
          </el-input> -->
          {{ activity.content }}
        </el-form-item>

        <el-form-item label="活动地点" prop="place">
          <!-- <el-input v-model="activity.place" /> -->
          {{ activity.place }}
        </el-form-item>
        <el-form-item label="活动举办方" prop="org">
          <!-- <el-input v-model="activity.org" /> -->
          {{ activity.org }}
        </el-form-item>

        <!-- 禁用人数的输入框 -->
        <el-form-item label="活动人数" prop="people">
          <!-- <el-input v-model.number="activity.people" :disabled="true"/> -->
          {{ activity.choosePeople }} / {{ activity.people }}
        </el-form-item>

        <el-form-item label="活动时间" prop="beginTime" size="medium">
          <!-- <el-date-picker type="date" placeholder="选择日期" v-model="activity.beginTime" style=""></el-date-picker> -->
          <!-- <el-date-picker
            v-model="activity.beginTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker> -->
          {{ activity.beginTime }}
        </el-form-item>

        <el-form-item label="活动积分" prop="score">
          <!-- <el-input v-model.number="activity.score" /> -->
          {{ activity.score }}
        </el-form-item>

        <el-form-item label="活动状态" prop="score">
          <!-- <el-switch
            v-model="kaiguan"
            active-text="活动可参加"
            inactive-text="活动不可参加">
          </el-switch> -->

          <div v-if="kaiguan">活动可参加</div>
          <div v-else>活动不可参加</div>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <!-- <el-button v-if="activity.choosePeople < activity.people && activity.status === 1"
                   type="success" @click="submitForm2('activity')">选择活动</el-button>
        <el-button v-else
                   type="info" disabled>选择活动</el-button> -->

        <el-button @click="resetForm2('activity')">关闭</el-button>
      </div>
    </el-dialog>

    <br>
    <!--表格-->
    <template>
      <el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column prop="name" label="活动名称" align="center" />
        <el-table-column prop="place" label="活动地点" align="center" />
        <!-- <el-table-column prop="image" label="图片" align="center">
          <template slot-scope="{ row }">
            <el-image style="width: auto; height: 100px; border: none; cursor: pointer" :src="row.image" />
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="totalPrice" label="总金额" align="center" /> -->
        <el-table-column prop="org" label="活动举办方" align="center" />

        <el-table-column prop="status" label="活动状态" align="center">
          <template slot-scope="scope">
            <span style="margin-right: 10px" v-if="scope.row.status == 0">不可参加</span>
            <span style="margin-right: 10px" v-if="scope.row.status == 1">可参加</span>
          </template>
        </el-table-column>


        <el-table-column prop="choosePeople,people" label="已选人数/需要人数" align="center">
          <template slot-scope="scope">
            {{ scope.row.choosePeople }} / {{ scope.row.people }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="people" label="需要人数" align="center" /> -->

        <el-table-column prop="beginTime" label="活动时间" align="center" />

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="update(scope.row.id, scope.row.choosePeople)">活动详情</el-button>

            <el-button type="warning" size="small" @click="choose(scope.row)">取消选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <br>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
// import { page, add, update, deleteById, selectById } from '@/api/emp.js'
import { orderPage, updateById, selectOrderById } from '@/api/order.js'
import { findAll } from '@/api/dept.js'
import { getToken } from '@/utils/auth'
import { page, insert, selectById, update, choose, myChoose, unChoose } from '@/api/activity.js'

export default {
  data() {
    return {
      kaiguan: true,


      background: true,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      dialogVisible2: false,

      /** 搜索的模型数据 */
      searchEmp: {
        name: '',
        place: '',
        org: ''
      },

      /** 表单的数据模型对象 */
      activityForm: {
        beginTime: "",
        content: "",
        image: "",
        name: "",
        org: "",
        people: null,
        place: "",
        score: null,
        status: 1
      },

      activity: {
        beginTime: "",
        content: "",
        createTime: "",
        id: 0,
        image: "",
        name: "",
        org: "",
        people: 0,
        choosePeople: 0, //
        place: "",
        score: 0,
        status: 1,
        updateTime: "",
        choosePeople: 0
      },

      deptList: [],

      beginTime: '',
      endTime: '',
      entrydate: '',

      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      token: { token: getToken() },

      /* 控制流程图 */
      // active: 1,

      selectedId: 0,

      // status: 20

    }
  },

  created () {
    // 先请求后端拿status啊
    // this.active = this.sToa(this.status)
  },

  watch: {
    entrydate(val) {
      if (val && val.length >= 2) {
        this.beginTime = val[0]
        this.endTime = val[1]
      } else {
        this.beginTime = ''
        this.endTime = ''
      }
    }
  },

  mounted() { // 钩子方法
    this.page() // 当页面加载完成后，发送异步请求，获取数据
    // findAll().then((result) => { // 请求部门数据
    //   this.deptList = result.data.data
    // })
  },

  methods: {
  /**
   * 点击保存

   * @param {Object} formName
   */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 先修改时间的格式
          // const str = this.activityForm.beginTime.replace(/T/, ' ').replace(/Z$/, '')
          // console.log(str)
          // this.activityForm.beginTime = str
          console.log(this.activityForm.beginTime)

          // 请求后端接口
          insert(this.activityForm).then((result) => {
            if (result.data.status == 200) {
              //修改成功
              this.$message.success("保存成功");
              // 刷新页面
              this.page()
            } else {
              this.$message.error(result.data.msg);
            }
          })

          // 关闭对话框
          this.dialogVisible = false

          // 清空数据模型
          this.activityForm = {
            beginTime: "",
            content: "",
            image: "",
            name: "",
            org: "",
            people: null,
            place: "",
            score: null,
            status: 1
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false
    },

    /**
     * 选择活动的接口

     * @param {Object} formName
     */
    submitForm2(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 先修改时间的格式
          // const str = this.activityForm.beginTime.replace(/T/, ' ').replace(/Z$/, '')
          // console.log(str)
          // this.activityForm.beginTime = str
          console.log(this.activityForm.beginTime)

          if (this.kaiguan === true) {
            this.activity.status = 1
          } else {
            this.activity.status = 0
          }

          // 请求后端接口
          update(this.activity).then((result) => {
            if (result.data.status == 200) {
              //修改成功
              this.$message.success("修改成功");
              // 刷新页面
              this.page()
            } else {
              this.$message.error(result.data.msg);
            }
          })

          // 关闭对话框
          this.dialogVisible2 = false

          // 清空数据模型
          this.activity = {
            beginTime: "",
            content: "",
            createTime: "",
            id: 0,
            image: "",
            name: "",
            org: "",
            people: 0,
            choosePeople: 0,
            place: "",
            score: 0,
            status: 1,
            updateTime: "",
            choosePeople: 0
          }
          this.kaiguan = true

        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm2(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible2 = false
    },
    handleClose(done) {
      // 确认的弹框
      this.$confirm('数据将不会保存，确认关闭？')
          .then(_ => {
            this.$refs['activityForm'].resetFields();
            done();
          })
          .catch(_ => {});
    },
    handleClose2(done) {
      // 确认的弹框
      this.$confirm('数据将不会保存，确认关闭？')
          .then(_ => {
            this.$refs['activity'].resetFields();
            done();
          })
          .catch(_ => {});
    },

    /**
     * 查询分页数据
     */
    page() {
      // console.log("调用Page。。。")
      myChoose( // 向后端发请求
        this.currentPage,
        this.pageSize
      ).then((res) => {
        // 响应数据的data里面有total和rows，去看接口文档
        this.totalCount = res.data.data.total
        this.tableData = res.data.data.records
      })
    },

    // 查询方法
     onSubmit() {
       this.currentPage = 1
       this.page()
     },
    // 清空
     clear() {
       this.searchEmp = {
        name: '',
        place: '',
        org: ''
      },
       this.beginTime = ''
       this.endTime = ''
       this.entrydate = ''
       this.page()
     },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    /**
     * 状态递增
     */
    addState () {
      if (this.active !== 4) this.active += 1
    },

    /**
     * 修改

     * @param {Object} id
     */
    update(id, choosePeople) {
      // 打开编辑窗口
      this.dialogVisible2 = true
      // 请求后端接口，回显数据
      selectById(id).then((result) => {
        if (result.data.status == 200) { // 200
          // 回显数据
          this.activity = result.data.data
          this.activity.choosePeople = choosePeople

          this.kaiguan = (this.activity.status === 1 ? true : false)

          this.selectedId = id
        }
      })
    },

    /**
     * 取消选择活动

     * @param {Object} activity
     */
    choose(activity) {

      this.$confirm('真的要退选活动吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {

                unChoose(activity).then((result) => {
                  if (result.data.status == 200) { // 200
                    this.page().then(() => {
                      this.$message({
                        type: 'success',
                        message: '退选成功!'
                      });
                    })
                  }
                  else {
                    this.$message({
                      type: 'error',
                      message: '问题发生...'
                    });
                  }
                })
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消退选'
                });
              });
    },

    /**
     * 保存修改的函数
     */
    // save () {
    //   let order = {
    //     id: this.selectedId,
    //     // status: this.aTos(this.active)
    //   }
    //   updateById(order).then((resp) => { // 请求后端接口
    //     if (resp.data.status == 200) { // 200
    //       this.dialogVisible = false
    //       this.orderPage() // 刷新页面
    //       this.$message({ message: '修改成功！', type: 'success' })
    //       // 删掉this.good的id
    //       this.active = 1
    //     } else {
    //       this.$message({ message: '修改失败！', type: 'error' })
    //     }
    //   })
    // },

    /**
     * 分页

     * @param {Object} val
     */
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val
      this.page()
    },

    /**
     * 删除员工信息

     * @param {Object} id
     */
    // deleteById(id) {
    //   this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     // 2. 发送AJAX请求
    //     deleteById(id).then((resp) => {
    //       if (resp.data.code == 1) {
    //         // 删除成功
    //         this.$message.success('恭喜你，删除成功')
    //         this.orderPage()
    //       } else {
    //         this.$message.error(resp.data.msg)
    //       }
    //     })
    //   }).catch(() => {
    //     // 用户点击取消按钮
    //     this.$message.info('已取消删除')
    //   })
    // },

    /**
     * 批量删除员工信息
     */
    // deleteByIds() {
    //   // 弹出确认提示框
    //   this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     // 用户点击确认按钮
    //     // 1. 创建id数组, 从 this.multipleSelection 获取即可
    //     for (let i = 0; i < this.multipleSelection.length; i++) {
    //       this.selectedIds[i] = this.multipleSelection[i].id
    //     }

    //     // 2. 发送AJAX请求
    //     deleteById(this.selectedIds).then((resp) => {
    //       if (resp.data.code == '1') {
    //         // 删除成功
    //         this.$message.success('恭喜你，删除成功')
    //         this.page()
    //       } else {
    //         this.$message.error(resp.data.msg)
    //       }
    //     })
    //   }).catch(() => {
    //     // 用户点击取消按钮
    //     this.$message.info('已取消删除')
    //   })
    // },

    /**
     * 文件上传相关

     * @param {Object} res
     * @param {Object} file
     */
    // handleAvatarSuccess(res, file) {
    //   this.emp.image = res.data
    //   console.log(this.emp.image)
    // },
    // beforeAvatarUpload(file) {
    //   const isJPG = file.type === 'image/jpeg'
    //   const isLt2M = file.size / 1024 / 1024 < 2
    //   if (!isJPG) {
    //     this.$message.error('上传头像图片只能是 JPG 格式!')
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 2MB!')
    //   }
    //   return isJPG && isLt2M
    // }
  }
}
</script>
<style>
.wapper {
  padding: 40px;
}
.wapperBtn {
  padding: 20px;

}
.center-btns {
  display: flex;
  padding-left: 30%;
}
</style>
